package servlet;

import dao.LoginDao;
import text.UserBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/checkServlet")
public class CheckServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        //读取用户填写的输入框中的内容
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkcode = request.getParameter("checkcode");

        //获取存储在session中的验证码字符串
        HttpSession session = request.getSession();
        //由于知道获取的是字符串，在这里可以直接类型转换
        String checkCode = (String) session.getAttribute("checkCode");

        if (checkCode != null && checkCode.equalsIgnoreCase(checkcode)) {
            //将session中存储的验证码字符串销毁，达到验证码只能使用一次的效果
            session.removeAttribute("checkCode");
            UserBean user = new UserBean();
            user.setUsername(username);
            user.setPassword(password);
            boolean flag = new LoginDao().login(user);
            if (flag) {
                //用户名密码正确
                //转发到正确的界面
                session.setAttribute("user", username);
                //request.setAttribute("user", username);
                response.sendRedirect(request.getContextPath() + "/findAllServlet");
            } else {
                //用户名密码错误
                request.setAttribute("userOrPasswordError", "用户名或密码错误");
                request.getRequestDispatcher("/index.jsp").forward(request, response);
            }
        } else {
            //验证码不正确的情况
            request.setAttribute("checkCodeError", "验证码不正确！");
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
